//
//  ClassifyViewController.m
//  BeautyClother
//
//  Created by dllo on 15/8/21.
//  Copyright (c) 2015年 宋爽. All rights reserved.
//

#import "ClassifyViewController.h"
#import "AsyncConnection.h"
#import "define.h"
#import "UIImageView+WebCache.h"
#import "ClassCell.h"
#import "ClassLayout.h"
#import "DetailViewController.h"
#import "MBProgressHUD.h"
#import "Reachability.h"
#import "CityDetailViewController.h"
#import "ViewController.h"

@interface ClassifyViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIPickerViewDataSource,UIPickerViewDelegate>

@property (nonatomic, retain) UITableView *table;
@property (nonatomic, retain) UICollectionView *collection;
@property (nonatomic, retain) NSMutableArray *countryArr;
@property (nonatomic, retain) NSMutableArray *array;
@property (nonatomic, copy) NSString *cid;
@property (nonatomic, retain) NSMutableArray *numArr;
@property (nonatomic, copy) NSString *cityid;
@property (nonatomic, retain) ClassLayout *layout;
@property (nonatomic,retain)UIButton *searchbutton;
@property (nonatomic, assign) CGFloat offWidth;
@property (nonatomic, assign) CGFloat offHeight;
@property (nonatomic, retain) MBProgressHUD *mb;
@property (nonatomic,retain)UIPickerView *pick;
@property (nonatomic,retain)NSString *string;
@property (nonatomic,retain)NSMutableArray *cityArr;
@end

@implementation ClassifyViewController

- (void)dealloc
{
    [_cityArr release];
    [_countryArr release];
    [_numArr release];
    [_layout release];
    [_mb release];
    [_array release];
    [_countryArr release];
    [_table release];
    [_collection release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.array = [NSMutableArray array];
        self.countryArr = [NSMutableArray array];
        
        self.numArr = [NSMutableArray array];
        self.offWidth = [[UIScreen mainScreen]bounds].size.width / 375;
        self.offHeight = [[UIScreen mainScreen]bounds].size.height / 667;
        self.cityArr = [NSMutableArray array];
        self.cityArr = @[@"请选择",@"北京",@"天津市",@"河北省",@"山西省",@"内蒙古",@"辽宁省",@"吉林省",@"黑龙江",@"上海",@"江苏省",@"浙江省",@"安徽省",@"福建省",@"江西省",@"山东省",@"河南省",@"湖北省",@"湖南省",@"广东省",@"广西省",@"海南省",@"重庆省",@"四川省",@"贵州省",@"云南省",@"西藏",@"陕西省",@"甘肃省",@"青海省",@"宁夏省",@"新疆"].mutableCopy;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 50)];
    title.font = [UIFont boldSystemFontOfSize:20];
    title.textColor = [UIColor colorWithRed:0 green:0.5 blue:255/255 alpha:0.8];
    title.textAlignment = NSTextAlignmentCenter;
    title.text = @"去旅行";
    self.navigationItem.titleView = title;
    
    
    [self connection];
    [self createTable];
    [self createCollection:@"0"];
    self.automaticallyAdjustsScrollViewInsets = NO;
    BOOL net = [ClassifyViewController judgeConnect];
    if (net) {
        
        
        
        self.mb = [[MBProgressHUD alloc]initWithView:[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)]];
        [self.view addSubview:self.mb];
        self.mb.labelText = @"努力加载着";
        
        [self.mb show:YES];
    }
    
    CGFloat offwidth = [UIScreen mainScreen].bounds.size.width / 375;
    
    UIButton *mapbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    [mapbutton setBackgroundImage:[UIImage imageNamed:@"iconfont-mainicongps.png"] forState:UIControlStateNormal];
//    [mapbutton setTitleColor:[UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1] forState:UIControlStateNormal];
    mapbutton.frame = CGRectMake(300 * offwidth, 0, 40, 30);
    [mapbutton addTarget:self action:@selector(mapAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:mapbutton];
    
    
    UIButton *photo = [UIButton buttonWithType:UIButtonTypeSystem];
    photo.frame = CGRectMake(10 * offwidth, 0, 40, 30);
    [photo addTarget:self action:@selector(photoAction:) forControlEvents:UIControlEventTouchUpInside];
    [photo setBackgroundImage:[UIImage imageNamed:@"iconfont-jinlingyingcaiwangtubiao06.png"] forState:UIControlStateNormal];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:photo];
    
}
- (void)photoAction:(UIButton *)button
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:^{
        }];
        
        
    }
    else
    {
        NSLog(@"没有摄像头");
    }
    
}

- (void)mapAction:(UIButton *)button
{
    
    
    ViewController *view = [[ViewController alloc] init];
    view.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:view animated:YES];
    
    
    
    
    
}


+ (BOOL)judgeConnect
{
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    NetworkStatus sta = [reach currentReachabilityStatus];
    if (sta == NotReachable) {
        return NO;
    }else{
        return YES;
    }
}

- (void)connection
{
    
    NSDictionary *dic = @{
                          @"client_id":@"qyer_ios",
                          @"client_secret":@"cd254439208ab658ddf9",
                          @"count":@"20",
                          @"lat":@"38.88268566409049",
                          @"lon":@"121.5391764987836",
                          @"page":@"1",
                          @"track_app_channel":@"App%2520Store",
                          @"track_app_version":@"6.6",
                          @"track_device_info":@"iPhone%25205s@",
                          @"track_deviceid":@"2CC19978-A0E5-49F2-9719-59DC5EDE6BBB",
                          @"track_os":@"ios%25208.4",
                          @"v":@"1",
                          };
    [AsyncConnection asyncConnection:CLASS parmaters:dic block:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        self.numArr = [dic objectForKey:@"data"];
        [self.countryArr addObjectsFromArray:[[self.numArr objectAtIndex:0]objectForKey:@"hot_country"]];
        [self.countryArr addObjectsFromArray:[[self.numArr objectAtIndex:0]objectForKey:@"country"]];
        
        [self.table reloadData];
        [self.mb removeFromSuperview];
        if (self.countryArr.count % 3 == 0) {
            
            self.layout.height =  self.countryArr.count / 3 * 120*_offHeight;
        }else
        {
            self.layout.height = (self.countryArr.count / 3 + 1) * 120*_offHeight;
        }
        [self.collection reloadData];
        
        
    }path:@"class_country"];
    
    
    
    
}


- (void)createTable
{
    
    self.table = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, 100 *_offWidth, self.view.frame.size.height - 112) style:UITableViewStylePlain];
    [self.view addSubview:self.table];
    self.table.backgroundColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:0.1];
    self.table.delegate = self;
    self.table.dataSource = self;
    self.table.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.table release];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    [button setTitle:@"中国城市" forState:UIControlStateNormal];
    button.backgroundColor = [UIColor clearColor];
    button.frame = CGRectMake(0, self.view.frame.size.height - 350, 100 * _offWidth, 60 * _offHeight);
    [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [self.table addSubview:button];
    
    self.searchbutton = [UIButton buttonWithType:UIButtonTypeSystem];
    [_searchbutton setTitle:@"搜索地图" forState:UIControlStateNormal];
    _searchbutton.backgroundColor = [UIColor clearColor];
    _searchbutton.frame = CGRectMake(0, self.view.frame.size.height - 170, 100 * _offWidth, 60 * _offHeight);
    
    [_searchbutton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [_searchbutton addTarget:self action:@selector(searchButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.table addSubview:_searchbutton];
    // _searchbutton.hidden = YES;
    
    self.pick = [[UIPickerView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 310, 80 * _offWidth, 160 * _offHeight)];
    _pick.dataSource = self;
    _pick.delegate = self;
    
    _pick.showsSelectionIndicator =YES;
    [self.table addSubview:_pick];

    
}

- (void)searchButtonAction:(UIButton *)button
{
    if (self.string != nil && ![self.string isEqualToString:@"请选择"]) {
        ViewController *view = [[ViewController alloc] init];
        view.localstr = self.string;
        [self.navigationController pushViewController:view animated:YES];
        [view release];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请选择地名" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
}

//列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}
//行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    
    
    return [self.cityArr count];
}

//列标题
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    
    return [self.cityArr objectAtIndex:row];
    
}
// 每列的宽度
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    
    
    return 80;
    
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    
    return 40;
    
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    self.string = [self.cityArr objectAtIndex:row];
    
}




- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.numArr.count;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[NSString stringWithFormat:@"%ld", indexPath.row]];
    if (cell == nil) {
        
        //  static dispatch_once_t once;
        //        dispatch_once(&once, ^{
        //            if (indexPath.row == 0) {
        //                cell.backgroundColor = [UIColor redColor];
        //            }
        //
        //        });
        
        
        cell= [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[NSString stringWithFormat:@"%ld", indexPath.row]];
        cell.textLabel.text = [[self.numArr objectAtIndex:indexPath.row]objectForKey:@"cnname"];
        cell.textLabel.textColor = [UIColor colorWithRed:0 green:0.5 blue:255/255 alpha:0.8];
        
        cell.backgroundColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:(indexPath.row * 0.03)];
        
        
        
        cell.selectedBackgroundView = [[[UIView alloc] initWithFrame:cell.frame] autorelease];
        cell.selectedBackgroundView.backgroundColor = [UIColor whiteColor];
        
        
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [[self.view viewWithTag:20]removeFromSuperview];
    self.cid = [NSString stringWithFormat:@"%ld", indexPath.row];
    [self createCollection:self.cid];
    
}

- (void)createImage:(NSString *)cid
{
    UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(100 *_offWidth, 64, self.view.frame.size.width - 100 *_offWidth, 160*_offHeight)];
    [self.view addSubview:image];
    [image sd_setImageWithURL:[NSURL URLWithString:[[self.numArr objectAtIndex:cid.intValue] objectForKey:@"icon"]] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
    
    
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 80*_offHeight, image.frame.size.width, 40*_offHeight)];
    label.textColor = [UIColor whiteColor];
    
    label.font = [UIFont systemFontOfSize:15];
    
    label.text = [[self.numArr objectAtIndex:cid.intValue]objectForKey:@"describe"];
    
    [image addSubview:label];
    label.textAlignment = 1;
    
    [image release];
}


- (void)createCollection:(NSString *)cid
{
    
    if (self.numArr.count != 0) {
        [self.countryArr removeAllObjects];
        [self.collection removeFromSuperview];
        [self.countryArr addObjectsFromArray:[[self.numArr objectAtIndex:cid.intValue]objectForKey:@"hot_country"]];
        [self.countryArr addObjectsFromArray:[[self.numArr objectAtIndex:cid.intValue]objectForKey:@"country"]];
        
    }
    self.layout = [[ClassLayout alloc]init];
    self.collection = [[UICollectionView alloc]initWithFrame:CGRectMake(100*_offWidth, 69, self.view.frame.size.width - 100 *_offWidth, self.view.frame.size.height - 69 - 60 *_offHeight) collectionViewLayout:_layout];
    _layout.itemSize = CGSizeMake(80*_offWidth, 100*_offHeight);
    
    _layout.minimumLineSpacing = 20 *_offHeight;
    _layout.minimumInteritemSpacing = 20 *_offWidth;
    
    
    if (self.countryArr.count % 3 == 0) {
        _layout.height = self.countryArr.count / 3 * 120*_offHeight;
    }else
    {
        
        _layout.height = (self.countryArr.count / 3 + 1) * 120*_offHeight;
    }
    
    [self.view addSubview:self.collection];
    self.collection.delegate = self;
    self.collection.dataSource = self;
    self.collection.backgroundColor = [UIColor whiteColor];
    
    [self.collection registerClass:[ClassCell class] forCellWithReuseIdentifier:@"rrr"];
    [self.collection release];
    
    
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    //    [self.mb removeFromSuperview];
    return self.countryArr.count;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    ClassCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"rrr" forIndexPath:indexPath];
    
    NSDictionary *dic = [self.countryArr objectAtIndex:indexPath.item];
    cell.image.layer.cornerRadius = 5;
    cell.image.layer.masksToBounds = YES;
    cell.title.font = [UIFont systemFontOfSize:15];
    [cell.image sd_setImageWithURL:[NSURL URLWithString:[dic objectForKey:@"photo"]] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
    cell.title.text = [dic objectForKey:@"cnname"];
    
    return cell;
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[[[self.countryArr objectAtIndex:indexPath.item]objectForKey:@"flag"] stringValue]isEqualToString:@"1"]) {
        
        
        DetailViewController *detail = [[DetailViewController alloc]init];
        
        detail.tid = [[self.countryArr objectAtIndex:indexPath.item]objectForKey:@"id"];
        detail.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:detail animated:YES];
    }
    else
    {
        CityDetailViewController *sigh = [[CityDetailViewController alloc]init];
        sigh.cityId = [[self.countryArr objectAtIndex:indexPath.item]objectForKey:@"id"];
        [self.navigationController pushViewController:sigh animated:YES];
        [sigh release];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
